#include "socketsAPI.h"

bool socketConnect(SOCKET *m_socket, char *host, char *port) {// Initialize Winsock.
    WSADATA wsaData;
    int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != NO_ERROR)
		printf("Client: Error at WSAStartup().\n");
    else
        printf("Client: WSAStartup() is OK.\n");

	// Create a socket.
    *m_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (*m_socket == INVALID_SOCKET) {
        printf("Client: socket() - Error at socket(): %ld\n", WSAGetLastError());
        WSACleanup();
        return false;
    }
	else
       printf("Client: socket() is OK.\n");

    // Connect to a server.
    sockaddr_in clientService;
    clientService.sin_family = AF_INET;
    // Just test using the localhost, you can try other IP address
	// @change the host
    clientService.sin_addr.s_addr = inet_addr(host);
	u_short u_port = atoi(port);
    clientService.sin_port = htons(u_port);

    if (connect(*m_socket, (SOCKADDR*)&clientService, sizeof(clientService)) == SOCKET_ERROR) {
        printf("Client: connect() - Failed to connect.\n");
        WSACleanup();
        return false;
    }
    else {
       printf("Client: connect() is OK.\n");
       printf("Client: Can start sending and receiving data...\n");
    }

    // Send and receive data.
	printf("Connected\n");
	return true;
}

void sendMessage(SOCKET *m_socket, char *s, int len) {
	int bytesSent = send(*m_socket, s, len, 0);
	if(bytesSent == SOCKET_ERROR)
		printf("Client: send() error %ld.\n", WSAGetLastError());
}

void receiveMessage(SOCKET *m_socket, char *ans) {
	int bytesRecv = SOCKET_ERROR;
	int pos = 0;
	while (true) {
		recv(*m_socket, &ans[pos], 1, 0);
		if (ans[pos] == '\n')
			break;
		pos++;
	}
	ans[pos] = 0;
	if( *ans != '0' )
		cout << "prolog answered: " << ans << endl;
}

char* quit(SOCKET *m_socket) {
	char *quit_m = "quit.\n";
	char *resp;
	resp = exchange(m_socket, quit_m);
	return resp;
}

char* exchange(SOCKET *m_socket, char* command) {
	

	//char *buffer = "comando(1, 2).\n";
	//char *buffer = "initialize.\n";
	
	//printf("sending: %s", command);
	sendMessage(m_socket, command, strlen(command));

	char* response = new char[256];
	receiveMessage(m_socket, response);
	
	return response;
}